import { Modal, Divider, Dropdown, Form, Icon, Menu, message, Avatar, Table, PageHeader, Popover, Tooltip, Breadcrumb } from 'antd';
import React, { useState, useRef, useEffect, useContext } from 'react';
import UpdateForm from './UpdateForm';
import { FILE_FIELDS, DIR_OBJECT, FILE_OBJECT, DOWNLOAD_TYPES, XS_SIZE, TEST_USER, VDISK_NAME } from "@/generic/ConfigParams";
import style from './index.less';
import { TableListContext } from "../index";
import { sizeFormat, stringToDate, nameSort, sizeSort, dateSort } from "@/generic/Utils";
import { downloadApiRule, updateApiRule } from '../service';

export const handleUpdate = async (fields, vdiskName, currentPath, src, rw = true) => {

    const hide = message.loading('正在更新');
    if (currentPath == '/' && vdiskName == 'usr') {
        currentPath = `/${VDISK_NAME}`;
    }
    try {
        let _response = await updateApiRule({
            disk: vdiskName,
            srcfile: src.path,
            location: `${currentPath}/${fields.value}${src.ext}`,
            rw,
        })
        if (!_response.ok) {
            hide();
            return false;
        }
        else {
            hide();
            message.success('更新成功');
            return true;
        }
    } catch (error) {
        hide();
        message.error('更新失败请重试！');
        return false;
    }
}

export const downloadMenu = (record, vdiskName) => {

    const _menu = [];
    const file_type_value = record.type == 'image' ? 2 : 0;  // 差异化 图片和文档的下载类型
    DOWNLOAD_TYPES.forEach((item, i) => {
        if (file_type_value < item.type_value)
        _menu.push(
            <Menu.Item key={i}>
                <MockDownload record={record} vdiskName={vdiskName} fileIcon={item.icon} typeName={item.name} />
            </Menu.Item>,
        );
    })

    return <Menu>{_menu}</Menu>;
}

const MockDownload = props => {

    const { record, vdiskName, fileIcon, typeName } = props;

    const mockDownload = async e => {
        // e.preventDefault();
        const response = await downloadApiRule({}, vdiskName, record.path)
        console.log('==>> response', response, record)
        if (response.ok) {
            const fileBlob = await response.blob();
            const reader = new FileReader();
            reader.readAsDataURL(fileBlob);
            reader.onload = e => {

                let aTag = document.createElement("a");
                aTag.download = record.name;
                aTag.href = e.target.result;
                aTag.click()
            }
        }
    }

    return (
        <>
            <span onClick={e => mockDownload(e, record, vdiskName)}>
                <Icon type={fileIcon} />&nbsp;
                {typeName}
            </span>
        </>
        
    );
}

const mockPreview = async(e, setImgPath) => {
    const response = await downloadApiRule({}, 'root', '/0afcd.jpeg')
    console.log('==>> response', response)
    if (response.ok) {
        const fileBlob = await response.blob();
        const reader = new FileReader();
        reader.readAsDataURL(fileBlob);
        reader.onload = e => setImgPath(e.target.result);
    }
}

const createColumns = (vdisk, onNameClick, setModalVisible, setSrcfile, isMobile, redirect, setPreviewVisible, setImgPath) => {
    
    const superUserAuth = false;  // 以后加上用户权限认证 | 现在暂时用auth代替

    const vdiskName = vdisk();

    const nameClick = (record) => {

        if (record.isDir) {
            onNameClick(record);
            return;
        }
        redirect.push("/file/detail", {
            file: record,
            vdiskName: vdisk(),
        })
    }
    // name
    const renderName = {
        key: FILE_FIELDS.name.key, title: FILE_FIELDS.name.name, dataIndex: 'name', className: style.fileFirstCol,
        defaultSortOrder: 'ascend',
        sorter: nameSort,
        render: (_, record) => (
            <>
                <span style={{ cursor: "pointer" }}>
                    <span onClick={() => nameClick(record)}>
                        <Icon theme={DIR_OBJECT.theme} className={style.fileIcon}
                            style={{ color: (record.isDir ? DIR_OBJECT.color : FILE_OBJECT.color) }}
                            type={(record.isDir ? DIR_OBJECT.icon : FILE_OBJECT.icon)} />
                        <span style={{ marginLeft: "3px" }}>{record.name}</span>
                    </span>
                    {
                        !record.isDir &&
                        <span 
                            style={{ float: 'right' }} 
                            onClick={e => { mockPreview(e, setImgPath); setPreviewVisible(true) }}
                        >
                            <Icon type="eye" theme="twoTone" />
                        </span>
                    }
                </span>
            </>
        ),
    };
    const renderSize = {
        key: FILE_FIELDS.size.key, title: FILE_FIELDS.size.name, dataIndex: 'size', width: '15%',
        sorter: sizeSort,
        render: (size, record) => {
            if (record.isDir){
                return (<span>-</span>);
            }
            const res = sizeFormat(size, 0, 1);
            return (
                <span>{res[0]} {res[1]}</span>
            )
        },
    };
    const columns = [renderName, renderSize]
    if (!isMobile) {
        const renderModified = {
            key: FILE_FIELDS.modified.key, title: FILE_FIELDS.modified.name, dataIndex: 'modified', width: '20%',
            sorter: dateSort,
            render: (date, _) => <span>{stringToDate(date)}</span>,
        }
        columns.push(renderModified);

        if (vdiskName == "pub" ? true : false || superUserAuth) {
            const renderOwner = {
                key: FILE_FIELDS.owner.key, title: FILE_FIELDS.owner.name, dataIndex: 'owner', width: '10%',
                render: () => <span>{TEST_USER}</span>,
            }
            columns.push(renderOwner);
        }

        const renderOpts = {
            key: FILE_FIELDS.option.key, title: FILE_FIELDS.option.name, dataIndex: 'option', width: '10%',
            render: (_, record) => {

                const opts = [
                    <a key="0" onClick={() => {
                        setModalVisible(true);
                        setSrcfile(record);
                    }}>
                        <Icon type="edit" />
                    </a>,
                ];
                if (!record.isDir) {

                    return opts.concat(
                        <Divider key="1" type="vertical" />,
                        <Dropdown key="2" overlay={downloadMenu(record, vdiskName)} placement="bottomRight">
                            <a><Icon type="download" /></a>
                        </Dropdown>,
                    );
                }

                return opts;
            },
        }
        columns.push(renderOpts);
    }

    return columns
}

const DirsTable = props => {

    const { currentPath, isMobile, rowSelection, onRow, vdisk, onNameClick, tableRefresh, rowSize } = props;
    const contextOpts = useContext(TableListContext);
    const tableData = contextOpts.tableData.param;
    const [data, setData] = useState([]);
    const [modalVisible, setModalVisible] = useState(false);
    const [srcfile, setSrcfile] = useState();
    const [previewVisible, setPreviewVisible] = useState(false);
    const [imgPath, setImgPath] = useState();

    const columns = createColumns(vdisk, onNameClick, setModalVisible, setSrcfile, isMobile, props.history, setPreviewVisible, setImgPath);

    useEffect(() => {  // 
        // console.log("==>>> tableData 111", tableData)
        if (tableData instanceof Promise) {
            tableData.then(content => {
                setData(content);
                contextOpts.loading.dispatch({ type: 'loading', value: false })
            })
        }
    }, [tableData]);

    return (
        <div className={style.filesTable}>
            <Table
                columns={columns}
                // rowKey={record => record.login.uuid}
                dataSource={data}
                pagination={{}}
                loading={contextOpts.loading.param}
                rowSelection={rowSelection}
                onRow={onRow}
                size={rowSize}
            />
            <Modal visible={previewVisible} footer={null} onCancel={() => setPreviewVisible(false)}>
                <img alt="example" style={{ width: '100%' }} src={imgPath} />
                <Avatar src={imgPath} shape="square" size={64} alt="文件" />
            </Modal>
            <UpdateForm 
                onSubmit={async value => {

                    const success = await handleUpdate(value, vdisk(), currentPath, srcfile);
                    if (success) {

                        setModalVisible(false);
                        tableRefresh();
                    }
                }}
                onCancel={() => setModalVisible(false)}
                modalVisible={modalVisible}
                srcfile={srcfile}
            />
        </div>
    )
}

export default DirsTable;